package pers.litao.bit.user.exception;



import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import pers.litao.bit.commons.utils.Constant;
import pers.litao.bit.commons.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 李涛
 * @date 2020-07-10 14:31
 */
//@ResponseBody
@RestControllerAdvice
public class UserExceptionControllerAdvice {

    /**
     * 数据校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R hadleVaildException(MethodArgumentNotValidException e){
        Map<String,String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach(item -> {
            String message = item.getDefaultMessage();
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(Constant.ResponseCode.SUBMIT_DATA_ILLEGALITY.getCode(),
                Constant.ResponseCode.SUBMIT_DATA_ILLEGALITY.getMsg(),map);
    }
    @ExceptionHandler(value = Exception.class)
    public R allException(Exception e){
        return R.error(Constant.ResponseCode.SERVER_EXCEPTION.getCode(),
                Constant.ResponseCode.SERVER_EXCEPTION.getMsg() +":"+e.getMessage(),null);
    }
}
